﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// .net core web api处理请求类
    /// </summary>
    public class ControllersWebAPIHelper
    {

        /// <summary>
        /// 根据表名创建Controllers类
        /// </summary>
        /// <param name="strFilePath">保存路径</param>
        /// <param name="strProjectName">项目名</param>
        /// <param name="strTableName">表名</param>
        public static void CreateControllersClass(string strFilePath, string strProjectName, string strTableName, string strTableComment, string strDBName)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");

            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);

            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes

            Directory.CreateDirectory(strFilePath);
            StreamWriter sw = new StreamWriter(strFilePath + "\\" + strClassName + "Controller.cs", false, Encoding.GetEncoding("utf-8"));

            sw.WriteLine("using Microsoft.AspNetCore.Http;");
            sw.WriteLine("using Microsoft.AspNetCore.Mvc;");
            sw.WriteLine("using System.Collections.Generic;");
            sw.WriteLine("using System.Linq;");
            sw.WriteLine("using Microsoft.EntityFrameworkCore;");
            sw.WriteLine("using " + strProjectName + ".API.Data;");
            sw.WriteLine("using " + strProjectName + ".Models;");
            sw.WriteLine("using System;");
            sw.WriteLine("using System.Threading.Tasks;");
            sw.WriteLine("using Microsoft.AspNetCore.Authorization;");
            sw.WriteLine("using Senparc.CO2NET.Extensions;");
            sw.WriteLine("using " + strProjectName + ".Utility.Helper;");
            sw.WriteLine("using " + strProjectName + ".API.Filters;");
            sw.WriteLine("");
            sw.WriteLine("namespace " + strProjectName + ".API.Controllers");
            sw.WriteLine("{");
            sw.WriteLine("    /// <summary>");
            sw.WriteLine("    /// " + strTableComment + "类，定义了CURD相关操作");
            sw.WriteLine("    /// </summary>");
            sw.WriteLine("    [Produces(\"application/json\")]");
            sw.WriteLine("    [Route(\"api/[controller]\")]");
            sw.WriteLine("    [ApiController]");
            sw.WriteLine("    [Authorize]");
            sw.WriteLine("    public class " + strClassName + "Controller : BaseController<" + strClassName + "Controller>");
            sw.WriteLine("    {");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// " + strClassName + "Controller");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        public " + strClassName + "Controller(" + strProjectName + "ApiContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)");
            sw.WriteLine("        {");
            sw.WriteLine("          ");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 分页显示" + strTableComment + "数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"page\">分页</param>");
            sw.WriteLine("        /// <param name=\"limit\">每页显示数量</param>");
            sw.WriteLine("        /// <returns></returns>");
            sw.WriteLine("        [HttpGet]");
            sw.WriteLine("        [Route(\"/api/" + strTableNameLower + "\")]");
            sw.WriteLine("        public async Task<IActionResult> GetByPage(int page, int limit)");
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            if (!string.IsNullOrEmpty(CommonHelper.GetDetailsSelectJoinList(strDBName, strTableName)))
            {
                sw.WriteLine("                var result = from item in _context.Set<" + strClassName + ">()");
                // sw.WriteLine("                             " + CommonHelper.GetDetailsSelectJoinList(strDBName, strTableName));
                sw.WriteLine("                             select new");
                sw.WriteLine("                             {");
                sw.WriteLine(CommonHelper.GetLeftSelectColumnNameAPI(strProjectName,strDBName, strTableName, "item"));
                // sw.WriteLine(CommonHelper.GetDetailsSelectJoinColumn(strDBName, strTableName, strPrimaryKey, CommonHelper.GetLeftSelectColumnName2(strProjectName, strDBName, strTableName, "item")));
                sw.WriteLine("                              };");
                sw.WriteLine("                var list = await result.OrderByDescending(t => t." + strPrimaryKey + ").Skip((page - 1) * limit).Take(limit).ToListAsync();");
                sw.WriteLine("                var count = result.LongCount();");
                //sw.WriteLine("                AddLogs(7, \"查询LINQ=\" + result.Expression.ToString() + \",DATA=\" + list.ToJson(), \"FP71000\");");
                sw.WriteLine("                if (count <= 0)");
                sw.WriteLine("                {");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"暂无数据\", count = 0 });");
                sw.WriteLine("                }");
                sw.WriteLine("                else");
                sw.WriteLine("                {");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"success\", data = list, page = page, limit = limit, count = count, total_page = count / limit });");
                sw.WriteLine("                }");
            }
            else
            {
                sw.WriteLine("                var result = _context." + strTableName + ".Where(t => t." + strPrimaryKey + " > 0);");
                sw.WriteLine("                var count = result.LongCount();");
                sw.WriteLine("                var list =  await result.OrderByDescending(t => t.created_at).Skip((page - 1) * limit).Take(limit).ToListAsync();");
                //sw.WriteLine("                AddLogs(7, \"查询LINQ=\" + result.Expression.ToString() + \",DATA=\" + list.ToJson(), \"FP71000\");");
                sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = list, count = count });");
            }

            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> GetDataByPage\");");
            sw.WriteLine("                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.List, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            //sw.WriteLine("        /// <summary>");
            //sw.WriteLine("        /// 获取" + strTableComment + "表中数据填充下拉表单");
            //sw.WriteLine("        /// </summary>");
            //sw.WriteLine("        /// <returns>返回数据列表</returns>");
            //sw.WriteLine("        [HttpGet]");
            //sw.WriteLine("        [Route(\"/api/" + strTableNameLower + "/select\")]");
            //sw.WriteLine("        public async Task<IActionResult> Select()");
            //sw.WriteLine("        {");
            //sw.WriteLine("            try");
            //sw.WriteLine("            {");
            //sw.WriteLine("                var list = await _context." + strTableName + ".OrderByDescending(t => t.created_at).ToListAsync();");
            ////sw.WriteLine("                AddLogs(7, \"查询下拉填充,DATA=\" + list.ToJson(), \"FP72000\");");
            //sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = list });");
            //sw.WriteLine("            }");
            //sw.WriteLine("            catch (Exception ex)");
            //sw.WriteLine("            {");
            //sw.WriteLine("                log.Fatal(ex, \" -> Select\");");
            //sw.WriteLine("                return Json(new { code = 1, msg = ex.Message });");
            //sw.WriteLine("            }");
            //sw.WriteLine("        }");
            //sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 根据ID获取" + strTableComment + "详情");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
            sw.WriteLine("        /// <returns>返回" + strTableComment + "详情</returns>");
            sw.WriteLine("        [HttpGet(\"/api/" + strTableNameLower + "/{id}\")]");
            if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            {
                sw.WriteLine("        public async Task<IActionResult> GetById(long id)");
            }
            else
            {
                sw.WriteLine("        public async Task<IActionResult> GetById(int id)");
            }
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Information(\"id=\" + id);");
            sw.WriteLine("                var result = await _context." + strTableName + ".Where(t => t." + strPrimaryKey + " == id).Select(item => (new");
            sw.WriteLine("                {");
            sw.WriteLine(CommonHelper.GetSelectColumnNameForGetById(strProjectName, strDBName, strTableName, "item"));
            sw.WriteLine("                })).FirstOrDefaultAsync();");

            sw.WriteLine("                if (result == null)");
            sw.WriteLine("                {");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"数据为空\", count = 0 });");
            sw.WriteLine("                }");
            sw.WriteLine("                else");
            sw.WriteLine("                {");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"success\", data = result });");
            sw.WriteLine("                }");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Details\");");
            sw.WriteLine("                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Select, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 新增" + strTableComment + "");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"" + strTableNameSpec + "\">构造" + strTableComment + "对象数据</param>");
            sw.WriteLine("        /// <returns>返回新增的" + strTableComment + "</returns>          ");
            sw.WriteLine("        [HttpPost]");
            sw.WriteLine("        [Route(\"/api/" + strTableNameLower + "\")]");
            sw.WriteLine("        public async Task<IActionResult> Create(" + strClassName + " " + strTableNameSpec + ")");
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Information(" + '"' + strTableNameSpec + '=' + '"' + " + " + strTableNameSpec + ".ToJson()" + ");");
            if (CommonHelper.ChecktCreatedAtKey(strTableName, "created_at"))
            {
                sw.WriteLine("                " + strTableNameSpec + ".created_at = DateTime.Now;");
            }
            if (CommonHelper.ChecktCreatedAtKey(strTableName, "client_ip"))
            {
                sw.WriteLine("                " + strTableNameSpec + ".client_ip = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4()!.ToString();");
            }
            sw.WriteLine("                //_context." + strTableName + ".Add(" + strTableNameSpec + ");");
            sw.WriteLine("                await _context.SaveChangesAsync();");
            //sw.WriteLine("                AddLogs(4, \"新增," + strTableNameSpec + "=\" + " + strTableNameSpec + ".ToJson(), \"FP41000\");");
            sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = " + strTableNameSpec + " });");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Create\");");
            sw.WriteLine("                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 根据ID更新" + strTableComment + "");
            sw.WriteLine("        /// </summary>");
            //sw.WriteLine("        /// <param name=\"id\">ID</param>");
            sw.WriteLine("        /// <param name=\"" + strTableNameSpec + "\">构造" + strTableComment + "对象数据</param>");
            sw.WriteLine("        /// <returns></returns>");
            sw.WriteLine("        [HttpPost]");
            sw.WriteLine("        [Route(\"/api/" + strTableNameLower + "/update\")]");
            sw.WriteLine("        public async Task<IActionResult> Update(" + strClassName + " " + strTableNameSpec + ")");
            //if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            //{
            //    sw.WriteLine("        public async Task<IActionResult> Update(long id, " + strClassName + " " + strTableNameSpec + ")");
            //}
            //else
            //{
            //    sw.WriteLine("        public async Task<IActionResult> Update(int id, " + strClassName + " " + strTableNameSpec + ")");
            //}
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            //sw.WriteLine("                log.Information(" + CommonHelper.GetSaveLogColumnName(strTableName, strTableNameSpec) + ");");
            sw.WriteLine("                log.Information(" + '"' + strTableNameSpec + '=' + '"' + " + " + strTableNameSpec + ".ToJson()" + ");");
            sw.WriteLine("                var item = _context." + strTableName + ".FirstOrDefault(c => c." + strPrimaryKey + " == " + strTableNameSpec + "." + strPrimaryKey + ");");
            sw.WriteLine("                if (item != null)");
            sw.WriteLine("                {");
            sw.WriteLine(CommonHelper.GetUpdateItems(strDBName, strTableNameSpec, strTableName));
            sw.WriteLine("                    //_context." + strTableName + ".Update(item);");
            sw.WriteLine("                    await _context.SaveChangesAsync();");
            sw.WriteLine("                }");
            sw.WriteLine("");
            //sw.WriteLine("                AddLogs(6, \"编辑ID=\" + id+ \"," + strTableNameSpec + "=\" + " + strTableNameSpec + ".ToJson(), \"FP61000\");");
            sw.WriteLine("                return Json(new { code = 0, msg = \"更新成功\"});");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Update\");");
            sw.WriteLine("                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Update, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("        ");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 删除" + strTableComment + "");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"id\">ID</param>");
            sw.WriteLine("        /// <returns>返回是否删除成功</returns>");
            sw.WriteLine("        [HttpPost]");
            sw.WriteLine("        [Route(\"/api/" + strTableNameLower + "/del/{id}\")]");
            if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            {
                sw.WriteLine("        public async Task<IActionResult> Delete(long id)");
            }
            else
            {
                sw.WriteLine("        public async Task<IActionResult> Delete(int id)");
            }

            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Information(\"id=\"" + " + id" + ");");
            sw.WriteLine("                var item = _context." + strTableName + ".Find(id);");
            sw.WriteLine("                if (item != null)");
            sw.WriteLine("                {");
            sw.WriteLine("                    //_context." + strTableName + ".Remove(item);");
            sw.WriteLine("                    await _context.SaveChangesAsync();");
            sw.WriteLine("                }");
            sw.WriteLine("");
            sw.WriteLine("                return Json(new { code = 0, msg = \"删除成功\" });");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Delete\");");
            sw.WriteLine("                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Delete, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("    }");
            sw.WriteLine("}");
            sw.Close();

        }
    }
}
